package com.taobao.report.util.excel.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by Administrator on 2016/7/22.
 * 文件上传
 */
public class FileUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
    @Value("#{configProperties['resourceIP']}")
    private String resourceIP;
    @Value("#{configProperties['fileMax']}")
    private static Long fileMax;


    /**
     * 生成文件
     * @param stream
     * @param path
     * @param filename
     * @throws Exception
     */
    public static void saveFileFromInputStream(InputStream stream,String path,String filename) throws Exception
    {
        File dir = new File(path);
        if (!dir.exists()){   //如果目录不存在就创建目录
            dir.mkdirs();
        }
        FileOutputStream fs = new FileOutputStream(path + File.separator + filename);
        byte[] buffer =new byte[1024*1024];
        int byteread = 0;
        while ((byteread=stream.read(buffer))!=-1)
        {
            fs.write(buffer,0,byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }
    /**
     * 保存图片
     * @param file
     * @param filPatch
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String saveImageFile(MultipartFile file,String fileHp, String filPatch,String fileName) throws Exception{

        if(file == null){
            logger.error("上传文件不能够为空");
            throw new Exception("上传文件不能够为空");
        }
        String sourceName = file.getOriginalFilename(); // 原始文件名

        if(sourceName==null||"".equals(sourceName)){
            logger.error("上传文件不能够为空");
            throw new Exception("上传文件不能够为空");
        }
        if(file.getSize() > 10000000){
            logger.error("上传失败：文件大小不能超过10M");
            throw new Exception("上传失败：文件大小不能超过10M");
        }
        if(file.getSize()>0){
            saveFileFromInputStream(file.getInputStream(), fileHp + File.separator + filPatch, fileName);
        }else{
            logger.error("上传文件不能够为空");
            throw new Exception("上传文件不能够为空");
        }
       return filPatch + File.separator + fileName;
    }
}
